﻿#include "logThread.h"

LogThread::LogThread()
{

#ifdef Q_OS_ANDROID
    _outRootDir = "/storage/emulated/0/Download/Log/";
#else
    _outRootDir = "./Log/";
#endif


    deleteHistoryLog();

}

void LogThread::run(){
    while(1){

        _semaphore_logCount.acquire();
        if(_logQueue.size() == 0){
            qDebug() << "日志打印队列出错";
            return;
        }

        QFile file0("./logloglog.txt");      // 日志的日志

        file0.open(QIODevice::Append);
        file0.write((QDateTime::currentDateTime().toString("HH-mm-ss.zzz")+"StartLogging CurrentLogSize:"+QString::number(_logQueue.size())+"\n").toUtf8());
        file0.close();

        _queueMutex.lock();
        stLog log = _logQueue.dequeue();
        _queueMutex.unlock();

        // 打印路径
        QString outdir = _outRootDir + QDateTime::currentDateTime().toString("yyyyMMdd") + "/" + log.type + "/";
        QDir dir;
        if (!dir.exists(outdir)) {
            dir.mkpath(outdir);     // 创建目录
        }
        QString date= QDateTime::currentDateTime().toString("yyyyMMdd_HH");
        QString suffix = log.type=="" ? "" : ("_" + log.type);
        QString outpath = outdir + "/Log_" + DEBUG_SOFTWARE_NAME + "_" + date + suffix + ".txt";

        // 执行打印
        QFile file(outpath);
        bool res = file.open(QIODevice::Append);
        QString currentTime = QDateTime::currentDateTime().toString("HH-mm-ss.zzz");
        res = file.write((log.text + "\n").toUtf8());
        file.close();

        file0.open(QIODevice::Append);
        file0.write((QDateTime::currentDateTime().toString("HH-mm-ss.zzz")+"EndLogging\n").toUtf8());
        file0.close();
    }
}


void LogThread::write(QString text, QString type){

    _queueMutex.lock();
    _logQueue.enqueue(stLog(text, type));
    _queueMutex.unlock();
    _semaphore_logCount.release();

    return;

}



void LogThread::deleteHistoryLog(){     // 删除时间太早的Log文件

    QDir dir(_outRootDir);
    if(!dir.exists()){
        return;
    }
    // 删除日期范围
    QDateTime curDate = QDateTime::currentDateTime();
    QDateTime delDate = curDate.addDays(-_deleteTime);
    QString   endStr = delDate.toString("yyyyMMdd");
    QString   startStr = "20240101";
    // 获取路径下文件夹列表
    dir.setFilter(QDir::Dirs);
    QFileInfoList list = dir.entryInfoList();
    for(int i = 0; i < list.size(); ++ i){
        QFileInfo fileInfo = list.at(i);
        if(fileInfo.fileName() < endStr && fileInfo.fileName() > startStr){
            QDir dir(_outRootDir + fileInfo.fileName());
            dir.removeRecursively();
        }
    }
}
